package com.thinkgem.jeesite.modules.task.common;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.thinkgem.jeesite.modules.quartz.StatisticalAttendanceTask;
import com.thinkgem.jeesite.modules.task.common.entity.Task;



/**
 * Created by xiaole.zheng on 2017/5/8.
 */
@Component
public class DynamicScheduledTask {
    /**
     * logger日志.
     */
    private final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(this.getClass());
    //所有任务
    public static final Map<String, Task> TASKS = new ConcurrentHashMap<String, Task>(12);

    private ScheduledTaskRegistrar taskRegistrar;
    private TaskScheduler ct;

    public ScheduledTaskRegistrar getTaskRegistrar() {
        return taskRegistrar;
    }

    public void setTaskRegistrar(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;
    }

    public TaskScheduler getCt() {
        return ct;
    }

    public void setCt(TaskScheduler ct) {
        this.ct = ct;
    }

    /**
     * 启动一个线程。
     * 逻辑：先根据线程编号判断是否有线程在运行，有的话，先关闭线程再启动一个新线程
     * @param task
     */
    public  void start(Task task){
        Task oldTask =  TASKS.get(task.getTaskId());
        ScheduledFuture<?> taskHandle = null;
        if(null==oldTask){
            taskHandle = ct.schedule(new StatisticalAttendanceTask(task),new CronTrigger(task.getTrigger()));
            task.setTaskHandle(taskHandle);
            TASKS.put(task.getTaskId(),task);
        }else {
            taskHandle = oldTask.getTaskHandle();
            if (!taskHandle.isCancelled()) {
                /** false 表示当前任务若正在执行，则待其执行结束，再结束此任务. */
                taskHandle.cancel(false);
            }
            TASKS.remove(oldTask.getTaskId());
        }
    }

    public void stop(Task task){
        Task oldTask =  TASKS.get(task.getTaskId());
        if(null!=oldTask){
            ScheduledFuture<?> taskHandle = oldTask.getTaskHandle();
            if (!taskHandle.isCancelled()) {
                /** false 表示当前任务若正在执行，则待其执行结束，再结束此任务. */
                taskHandle.cancel(false);
            }
        }
        TASKS.remove(oldTask.getTaskId());
    }
}
